package be.jprojects.subscription.gui.tablepanels;

import java.awt.BorderLayout;

import javax.swing.DefaultListSelectionModel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import be.jprojects.subscription.controllers.ListenersController;
import be.jprojects.subscription.gui.CRUDButtonPanel;
import be.jprojects.subscription.gui.datamodels.NullSelectionModel;
import be.jprojects.subscription.gui.listeners.CRUDActionListener;
import be.jprojects.subscription.gui.renderers.ColorRowRenderer;
import be.jprojects.subscription.gui.renderers.HeaderRenderer;


public abstract class TablePanel extends JPanel implements ListSelectionListener, CRUDActionListener {
	protected JTable table;
	protected CRUDButtonPanel crudButtonPanel;
	private ListSelectionModel nullSelectionModel, singleSelectionModel;
	private JScrollPane scrollPane;
	
	public TablePanel(String name) {
		super.setName(name);
		setLayout(new BorderLayout());
		table = new JTable();
		table.setDefaultRenderer(Object.class, new ColorRowRenderer());

		table.getTableHeader().setDefaultRenderer(new HeaderRenderer());
		
		singleSelectionModel = new DefaultListSelectionModel();
		nullSelectionModel = new NullSelectionModel();
		
		table.setSelectionModel(singleSelectionModel);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.getSelectionModel().addListSelectionListener(this);

		scrollPane = new JScrollPane(table);
		//scrollPane.setViewport(table.getVisibleRect());
		crudButtonPanel = new CRUDButtonPanel(name);
		super.add(scrollPane, BorderLayout.CENTER);
		super.add(crudButtonPanel, BorderLayout.SOUTH);
		ListenersController.getInstance().addCRUDActionListener(super.getName(), this);
	}
	
	public abstract void cancelActionPerformed();
	public abstract void deleteActionPerformed();
	public abstract void newActionPerformed();
	public abstract void saveActionPerformed();
	public abstract void updateActionPerformed();
	public abstract void selectedIndexChanged(int index);
	
	
	protected void setSelectable(boolean selectable) {
		if (selectable) {
			table.setSelectionModel(singleSelectionModel);
			scrollPane.setEnabled(selectable);
		}
		else {
			table.setSelectionModel(nullSelectionModel);
			scrollPane.setEnabled(selectable);
		}
	}
	
	public void valueChanged(ListSelectionEvent e) {
		ListSelectionModel lsm = (ListSelectionModel) e.getSource();
		selectedIndexChanged(lsm.getLeadSelectionIndex());
	}
}
